package com.kt.kvw.generator;

import lombok.extern.slf4j.Slf4j;

import java.security.SecureRandom;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Created with IntelliJ IDEA.
 * Desc:
 *
 * @author: keen
 * Date: 2020-07-10
 * Time: 21:37
 */
@Slf4j
public class AuthCodeGenerator {

    /**
     * 验证码默认长度
     */
    private final static int DEFAULT_LENGTH = 4;

    /**
     * 验证码字母表
     */
    private static char[] WORD_SEQUENCE = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
            'W', 'X', 'Y', 'Z'};

    /**
     * 验证码数字表
     */
    private static char[] NUMBER_SEQUENCE = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    private static char[] WORD_NUMBER_SEQUENCE = new char[WORD_SEQUENCE.length + NUMBER_SEQUENCE.length];

    static {
        System.arraycopy(WORD_SEQUENCE, 0,
                WORD_NUMBER_SEQUENCE, 0, WORD_SEQUENCE.length);
        System.arraycopy(NUMBER_SEQUENCE, 0,
                WORD_NUMBER_SEQUENCE, WORD_SEQUENCE.length, NUMBER_SEQUENCE.length);
    }


    private static ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();

    public static String generatorWordAndNumberCode(int length) {
        return generator(length, WORD_NUMBER_SEQUENCE);
    }

    public static String generatorWordCode(int length) {
        return generator(length, WORD_SEQUENCE);
    }

    public static String generatorNumberCode(int length) {
        return generator(length, NUMBER_SEQUENCE);
    }


    private static String generator(int length, char[] codeSequence) {
        int len = getLength(length);
        char[] codes = new char[length];
        for (int i = 0; i < len; i++) {
            int index = threadLocalRandom.nextInt(codeSequence.length);
            codes[i] = codeSequence[index];
        }
        return new String(codes);
    }

    private static int getLength(int length) {
        if (length <= 0) {
            return DEFAULT_LENGTH;
        } else {
            return length;
        }
    }
}
